package com.hljx.config.dataBase;

import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

/**
 * @BelongsProject: hljx
 * @BelongsPackage: com.hljx.config
 * @Author: lp
 * @CreateTime: 2023-09-25  10:22
 * @Description: TODO
 * @Version: 1.0
 */
@Configuration
@MapperScan(value = "com.hljx.mapper.sm", sqlSessionFactoryRef = "SMSqlSessionFactory")
@EnableTransactionManagement
public class SMDataSourceConfig {

    @Bean(name = "SMDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.smdb")
    public DataSource getDateSource() {
        return DataSourceBuilder.create().build();
    }


    @Bean(name = "SMSqlSessionFactory")
    public SqlSessionFactory hisSqlSessionFactory(
            @Qualifier("SMDataSource") DataSource datasource) throws Exception {

        MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
        bean.setDataSource(datasource);
        bean.setMapperLocations(// 设置mybatis的xml所在位置
                new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/sm/*.xml"));
        return bean.getObject();
    }


    @Bean("SMSqlSessionTemplate")
    @Primary
    public SqlSessionTemplate hisSqlSessionTemplate(
            @Qualifier("SMSqlSessionFactory") SqlSessionFactory sessionFactory) {
        return new SqlSessionTemplate(sessionFactory);
    }

    @Bean
    public PlatformTransactionManager transactionManager(@Qualifier("SMDataSource")DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
}
